package org.agile4j.patterns.singleton;

import java.util.HashMap;
import java.util.Map;

class OneExtend {
    /**
     * 定义一个缺省的key值的前缀
     */
    private final static String DEFAULT_PREKEY = "Cache";

    /**
     * 缓存事例的容器
     */
    private static Map<String, OneExtend> map = new HashMap<String, OneExtend>();

    /**
     * 记录事例数，到了最大值返回1
     */
    private static int num = 1;

    /**
     * 最大值
     */
    private final static int NUM_MAX = 3;

    private OneExtend() {
        System.out.println(111);
    }

    /**
     * 类级内部类，让jvm实现同步
     */
    private static class SingletonHoder {
        public static OneExtend getInstance() {
            String key = DEFAULT_PREKEY + num;
            OneExtend oneExtend = map.get(key);
            if (oneExtend == null) {
                oneExtend = new OneExtend();
                map.put(key, oneExtend);
            }
            num++;
            if (num > NUM_MAX) {
                //如果事例序号达到最大数，赋值1
                num = 1;
            }
            return oneExtend;
        }
    }

    public static OneExtend getInstance() {
        return SingletonHoder.getInstance();
    }

}

public class SingletonDemo03 {
    public static void main(String[] args) {
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
        System.out.println(OneExtend.getInstance());
    }
}
